package com.chhuang.system.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chhuang.core.bean.QueryBean;
import com.chhuang.core.validation.ValidGroupSave;
import com.chhuang.system.bean.ChUserQueryBean;
import com.chhuang.system.consts.SysConstants;
import com.chhuang.system.po.ChRole;
import com.chhuang.system.po.ChUser;
import com.chhuang.system.po.ChUserRoleMap;
import com.chhuang.system.service.IChRoleService;
import com.chhuang.system.service.IChUserRoleMapService;
import com.chhuang.system.service.IChUserService;
import com.chhuang.utils.Assert;
import com.chhuang.utils.config.SysConfig;
import com.chhuang.utils.string.Md5Util;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/system/user")
public class ChUserController {
	private static final Log log = LogFactory.getLog(ChUserController.class);

	@Autowired
	private IChUserService chUserService;
	@Autowired
	private IChRoleService chRoleService;
	@Autowired
	private IChUserRoleMapService chUserRoleMapService;
	
	/**
	 * 获取当前登录用户信息
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/getUserInfo",method=RequestMethod.GET)
	@ResponseBody
	public Object getUserInfo(HttpServletRequest request) throws Exception{
		ChUser user = null;
		HttpSession session = request.getSession(false);
		if(session!=null){
			String userId = (String) session.getAttribute(SysConstants.USER_ID);
			if(Assert.isValidString(userId)){
				user = chUserService.findByPrimaryKey(userId);
			}
		}
		log.debug("获取当前登录用户的信息");
		return user==null?SysConstants.Symbol.EMPTY_JSONOBJECT:user;
	}
	
	/**
	 * 获取用户信息
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/findUserById",method=RequestMethod.POST)
	@ResponseBody
	public Object findUserById(String userId) throws Exception{
		ChUser user = null;
		if(Assert.isValidString(userId)){
			user = chUserService.findByPrimaryKey(userId);
		}
		log.debug("获取用户信息");
		return user==null?SysConstants.Symbol.EMPTY_JSONOBJECT:user;
	}
	
	/**
	 * 用户名是否已存在
	 * @param username
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/isUsedName",method=RequestMethod.POST)
	@ResponseBody
	public Object isUsedName(String username) throws Exception{
		JSONObject json = new JSONObject();
		List<ChUser> users = chUserService.findByUsername(username);
		if(Assert.isValidCollection(users)){
			json.put(SysConstants.Status.SUCCESS, true);
		}
		log.debug(username+" 已存在  "+json.toString());
		return json;
	}
	
	/**
	 * 修改用户信息
	 * @param request
	 * @param username
	 * @param nickname
	 * @param phone
	 * @param email
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/updateUserInfo",method=RequestMethod.POST)
	@ResponseBody
	public Object updateUserInfo(HttpServletRequest request,String nickname,String phone,String email) throws Exception{
		JSONObject json = new JSONObject();
		HttpSession session = request.getSession(false);
		if(session!=null){
			String userId = (String) session.getAttribute(SysConstants.USER_ID);
			if(Assert.isValidString(userId)){
				ChUser user = chUserService.findByPrimaryKey(userId);
				user.setNickname(nickname);
				user.setPhone(phone);
				user.setEmail(email);
				log.debug(nickname+";"+phone+";"+email);
				chUserService.update(user);
				json.put(SysConstants.Status.SUCCESS, true);
			}
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 修改密码
	 * @param request
	 * @param oldPassword
	 * @param password
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/updatePassword",method=RequestMethod.POST)
	@ResponseBody
	public Object updatePassword(HttpServletRequest request,String oldPassword,String password) throws Exception{
		JSONObject json = new JSONObject();
		HttpSession session = request.getSession(false);
		if(session!=null){
			String userId = (String) session.getAttribute(SysConstants.USER_ID);
			if(Assert.isValidString(userId)){
				ChUser user = chUserService.findByPrimaryKey(userId);
				if(user.getPassword().equals(Md5Util.md5(oldPassword, user.getUsername()))){
					user.setPassword(Md5Util.md5(password, user.getUsername()));
					log.debug(password);
					chUserService.update(user);
					json.put(SysConstants.Status.SUCCESS, true);
				}else{
					json.put(SysConstants.Status.RESULT, "原密码不正确");
				}
			}
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 获取用户列表
	 * @param userQueryBean
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/getList",method=RequestMethod.POST)
	@ResponseBody
	public Object getList(@RequestBody ChUserQueryBean userQueryBean) throws Exception{
		log.debug(userQueryBean.getPageSize()+";"+userQueryBean.getPageNum()
				+";"+userQueryBean.getOrderBy()+";"+userQueryBean.isDesc()
				+";"+userQueryBean.isOr());
		
		QueryBean<ChUser> queryBean = chUserService.seniorQuery(userQueryBean);
		
		return queryBean==null?SysConstants.Symbol.EMPTY_JSONOBJECT:queryBean;
	}
	
	/**
	 * 添加或修改用户信息
	 * @param user
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/editUser/{roleIds}",method=RequestMethod.POST)
	@ResponseBody
	public Object editUser(@RequestBody @Validated(value={ValidGroupSave.class}) ChUser user, BindingResult bindingResult,
			@PathVariable String roleIds) throws Exception{
		JSONObject json = new JSONObject();
		if(bindingResult.hasErrors()){
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, bindingResult.getAllErrors().get(0).getDefaultMessage());
			log.debug(json.toString());
			return json;
		}
		if(Assert.isValidString(user.getUserId())){
			ChUser temp = chUserService.findByPrimaryKey(user.getUserId());
			if(temp != null){
				user.setPassword(temp.getPassword());
			}
		}else{
			user.setPassword(Md5Util.md5(SysConfig.getValue(SysConstants.Config.INIT_PASSWORD), user.getUsername()));
		}
		if(chUserService.saveOrUpdate(user)>0){
			if(Assert.isValidString(user.getUserId())){
				chUserRoleMapService.deleteByUserId(user.getUserId());
			}
			if(Assert.isValidString(roleIds) && !SysConstants.Symbol.NEGATIVE_ONE.equals(roleIds)){
				String[] roleIdArray = roleIds.split(SysConstants.Symbol.COMMA);
				for(String roleId : roleIdArray){
					ChRole role = chRoleService.findByPrimaryKey(roleId);
					if(role!=null){
						ChUserRoleMap userRoleMap = new ChUserRoleMap();
						userRoleMap.setRoleId(roleId);
						userRoleMap.setUserId(user.getUserId());
						userRoleMap.setRoleOrder(role.getRoleOrder());
						chUserRoleMapService.save(userRoleMap);
					}
				}
			}
			json.put(SysConstants.USER_ID, user.getUserId());
			json.put(SysConstants.Status.SUCCESS, true);
		}else{
			json.put(SysConstants.Status.SUCCESS, false);
			json.put(SysConstants.Status.RESULT, "未知错误");
		}
		log.debug(json.toString());
		return json;
	}
	
	/**
	 * 重置密码
	 * @param userId
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/resetPassword",method=RequestMethod.POST)
	@ResponseBody
	public Object resetPassword(String ids) throws Exception{
		JSONObject json = new JSONObject();
		if(Assert.isValidString(ids)){
			String[] userIds = ids.split(SysConstants.Symbol.COMMA);
			for(String userId : userIds){
				ChUser user = chUserService.findByPrimaryKey(userId);
				if(user != null){
					user.setPassword(Md5Util.md5(SysConfig.getValue(SysConstants.Config.INIT_PASSWORD), user.getUsername()));
					chUserService.update(user);
				}
			}
			json.put(SysConstants.Status.SUCCESS, true);
		}
		log.debug(ids+":::"+json.toString());
		return json;
	}
	
	/**
	 * 删除用户信息
	 * @param ids
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/delUsers/{ids}",method=RequestMethod.DELETE)
	@ResponseBody
	public Object delUsers(@PathVariable String ids) throws Exception{
		JSONObject json = new JSONObject();
		if(Assert.isValidString(ids)){
			String[] userIds = ids.split(SysConstants.Symbol.COMMA);
			chUserService.deleteByUserIdArray(userIds);
			chUserRoleMapService.deleteByUserIdArray(userIds);
			json.put(SysConstants.Status.SUCCESS, true);
		}
		log.debug(ids+":::"+json.toString());
		return json;
	}
}
